<template>
  <div class="medical-packages-container">
    <div class="page-tools">
      <div class="search-box">
        <el-form :inline="true" :model="searchForm" class="form-inline">
          <el-form-item>
            <el-input v-model="searchForm.keyword" placeholder="搜索套餐名称/ID/适用人群" clearable>
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchForm.category" placeholder="分类" clearable>
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchForm.status" placeholder="状态" clearable>
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="searchPackages">搜索</el-button>
            <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="action-box">
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增套餐</el-button>
      </div>
    </div>

    <el-table 
      :data="filteredPackages.slice((pagination.currentPage - 1) * pagination.pageSize, pagination.currentPage * pagination.pageSize)"
      style="width: 100%"
      border
      v-loading="loading"
    >
      <el-table-column label="套餐ID" prop="id" width="100" />
      <el-table-column label="套餐名称" prop="name" min-width="180" />
      <el-table-column label="分类" prop="category" width="120" />
      <el-table-column label="适用人群" prop="targetGroup" min-width="150" />
      <el-table-column label="价格(元)" prop="price" width="100" />
      <el-table-column label="有效期" prop="validity" width="100" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag 
            :type="scope.row.status === '在售' ? 'success' : scope.row.status === '已下架' ? 'info' : 'warning'"
          >
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" prop="createdAt" width="120" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            :icon="View" 
            circle 
            size="small" 
            @click="handleView(scope.row)"
            title="查看详情"
          />
          <el-button 
            type="primary" 
            :icon="Edit" 
            circle 
            size="small" 
            @click="handleEdit(scope.row)"
            title="编辑"
          />
          <el-button 
            type="danger" 
            :icon="Delete" 
            circle 
            size="small" 
            @click="handleDelete(scope.row)"
            title="删除"
          />
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑套餐对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑医疗套餐' : '新增医疗套餐'" 
      width="650px"
    >
      <el-form 
        :model="packageForm" 
        label-width="100px"
        :rules="rules"
        ref="packageFormRef"
      >
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="packageForm.name" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="packageForm.category" placeholder="选择分类" style="width: 100%">
            <el-option 
              v-for="item in categoryOptions.filter(i => i.value)"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="适用人群" prop="targetGroup">
          <el-input v-model="packageForm.targetGroup" />
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
          <el-input-number v-model="packageForm.price" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="有效期" prop="validity">
          <el-input v-model="packageForm.validity" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="packageForm.status">
            <el-radio label="在售">在售</el-radio>
            <el-radio label="待上架">待上架</el-radio>
            <el-radio label="已下架">已下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="套餐描述" prop="description">
          <el-input v-model="packageForm.description" type="textarea" rows="3" />
        </el-form-item>
        
        <el-form-item label="包含项目">
          <div class="package-items">
            <div v-for="(item, index) in packageForm.items" :key="index" class="package-item">
              <el-input v-model="item.name" placeholder="项目名称" style="width: 180px" />
              <el-input-number v-model="item.count" :min="1" placeholder="次数" style="width: 100px" />
              <el-input v-model="item.desc" placeholder="描述" style="width: 200px" />
              <el-button type="danger" :icon="Delete" circle size="small" @click="removeItem(index)" />
            </div>
            <el-button type="primary" :icon="Plus" size="small" @click="addItem">添加项目</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看套餐详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="医疗套餐详情" 
      width="700px"
    >
      <div v-if="currentPackage" class="package-detail">
        <div class="detail-header">
          <h2>{{ currentPackage.name }}</h2>
          <el-tag :type="currentPackage.status === '在售' ? 'success' : currentPackage.status === '已下架' ? 'info' : 'warning'">
            {{ currentPackage.status }}
          </el-tag>
        </div>
        
        <div class="detail-info">
          <div class="info-item">
            <span class="label">套餐ID:</span>
            <span class="value">{{ currentPackage.id }}</span>
          </div>
          <div class="info-item">
            <span class="label">分类:</span>
            <span class="value">{{ currentPackage.category }}</span>
          </div>
          <div class="info-item">
            <span class="label">适用人群:</span>
            <span class="value">{{ currentPackage.targetGroup }}</span>
          </div>
          <div class="info-item">
            <span class="label">价格:</span>
            <span class="value">¥{{ currentPackage.price }}</span>
          </div>
          <div class="info-item">
            <span class="label">有效期:</span>
            <span class="value">{{ currentPackage.validity }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建日期:</span>
            <span class="value">{{ currentPackage.createdAt }}</span>
          </div>
        </div>
        
        <div class="detail-description">
          <h3>套餐描述</h3>
          <p>{{ currentPackage.description }}</p>
        </div>
        
        <div class="detail-items">
          <h3>包含项目</h3>
          <el-table :data="currentPackage.items" style="width: 100%" border>
            <el-table-column label="项目名称" prop="name" />
            <el-table-column label="次数" prop="count" width="80" />
            <el-table-column label="描述" prop="desc" />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { Search, Plus, Edit, Delete, Refresh, View } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { medicalPackages } from '../../mock';

// 加载状态
const loading = ref(false);

// 表格数据
const packagesData = ref([]);

// 获取数据
const fetchData = () => {
  loading.value = true;
  // 在实际应用中，这里应该是API调用
  // 目前使用mock数据
  packagesData.value = medicalPackages;
  loading.value = false;
};

onMounted(() => {
  fetchData();
});

// 搜索条件和过滤
const searchForm = reactive({
  keyword: '',
  category: '',
  status: ''
});

// 分类选项
const categoryOptions = [
  { value: '', label: '全部分类' },
  { value: '慢病管理', label: '慢病管理' },
  { value: '妇幼保健', label: '妇幼保健' }
];

// 状态选项
const statusOptions = [
  { value: '', label: '全部状态' },
  { value: '在售', label: '在售' },
  { value: '待上架', label: '待上架' },
  { value: '已下架', label: '已下架' }
];

// 搜索方法
const searchPackages = () => {
  // 实际应用中应该调用API进行搜索
  console.log('搜索条件:', searchForm);
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.category = '';
  searchForm.status = '';
  searchPackages();
};

// 表格分页设置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 处理分页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val;
};

const handleSizeChange = (val) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
};

// 过滤后的数据
const filteredPackages = computed(() => {
  let result = [...packagesData.value];
  
  // 关键词搜索
  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase();
    result = result.filter(item => 
      item.name.toLowerCase().includes(keyword) || 
      item.id.toLowerCase().includes(keyword) ||
      item.targetGroup.toLowerCase().includes(keyword)
    );
  }
  
  // 分类过滤
  if (searchForm.category) {
    result = result.filter(item => item.category === searchForm.category);
  }
  
  // 状态过滤
  if (searchForm.status) {
    result = result.filter(item => item.status === searchForm.status);
  }
  
  // 更新总数
  pagination.total = result.length;
  
  return result;
});

// 表单相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const packageFormRef = ref(null);

const packageForm = reactive({
  id: '',
  name: '',
  category: '',
  targetGroup: '',
  price: 0,
  validity: '',
  description: '',
  items: [],
  status: '待上架',
  createdAt: ''
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  targetGroup: [{ required: true, message: '请输入适用人群', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  validity: [{ required: true, message: '请输入有效期', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

// 添加项目
const addItem = () => {
  packageForm.items.push({
    name: '',
    count: 1,
    desc: ''
  });
};

// 删除项目
const removeItem = (index) => {
  packageForm.items.splice(index, 1);
};

// 处理新增
const handleAdd = () => {
  isEdit.value = false;
  // 重置表单
  Object.keys(packageForm).forEach(key => {
    if (key === 'items') {
      packageForm.items = [{ name: '', count: 1, desc: '' }];
    } else if (key === 'price') {
      packageForm.price = 0;
    } else if (key === 'status') {
      packageForm.status = '待上架';
    } else {
      packageForm[key] = '';
    }
  });
  
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row) => {
  isEdit.value = true;
  // 复制数据到表单
  Object.keys(packageForm).forEach(key => {
    if (key === 'items') {
      packageForm.items = [...row.items];
    } else {
      packageForm[key] = row[key];
    }
  });
  
  dialogVisible.value = true;
};

// 提交表单
const submitForm = () => {
  packageFormRef.value.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑现有套餐
        const index = packagesData.value.findIndex(item => item.id === packageForm.id);
        if (index !== -1) {
          packagesData.value[index] = { ...packageForm };
        }
        ElMessage.success('套餐更新成功');
      } else {
        // 添加新套餐
        const newPackage = { ...packageForm };
        newPackage.id = `MP-${String(packagesData.value.length + 1).padStart(3, '0')}`;
        newPackage.createdAt = new Date().toISOString().split('T')[0];
        packagesData.value.unshift(newPackage);
        ElMessage.success('套餐添加成功');
      }
      dialogVisible.value = false;
    } else {
      return false;
    }
  });
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除套餐"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际应用中应该调用API删除数据
    packagesData.value = packagesData.value.filter(item => item.id !== row.id);
    ElMessage({
      type: 'success',
      message: '删除成功'
    });
  }).catch(() => {});
};

// 套餐详情
const detailDialogVisible = ref(false);
const currentPackage = ref(null);

const handleView = (row) => {
  currentPackage.value = row;
  detailDialogVisible.value = true;
};
</script>

<style scoped>
.medical-packages-container {
  width: 100%;
}

.page-tools {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  align-items: center;
}

.action-box {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.package-items {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}

.package-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
}

.package-detail .detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.package-detail .detail-header h2 {
  margin: 0;
}

.package-detail .detail-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
}

.info-item .label {
  width: 100px;
  color: #606266;
}

.info-item .value {
  font-weight: 500;
}

.detail-description,
.detail-items {
  margin-top: 20px;
}

.detail-description h3,
.detail-items h3 {
  font-size: 16px;
  margin-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}
</style> 